package com.xin.web;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.xin.entity.*;
import com.xin.service.*;
import com.xin.util.CacheUtil;
import com.xin.util.DecryptionUtil;
import io.swagger.models.auth.In;
import lombok.extern.java.Log;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * <p>
 * 教师信息 前端控制器
 * </p>
 *
 * @author l1
 * @since 2017-10-19
 */
@Controller
@RequestMapping("/teacher")
@Log
public class UTeacherInfoController {

    @Value("${teacher.common.key}")
    private String teacherCommonKey;
    @Value("${teacher.common.secret}")
    private String teacherCommonSecret;
    @Value("${teacher.image.key}")
    private String teacherImageKey;
    @Value("${teacher.image.secret}")
    private String teacherImageSecret;

    @Autowired
    private UTeacherInfoService uTeacherInfoService;

    @Autowired
    private STeacherResourcesService sTeacherResourcesService;

    @Autowired
    private UWorkExperienceService uWorkExperienceService;

    @Autowired
    private UDegreeChangesService uDegreeChangesService;

    @Autowired
    private UTitleChangesService uTitleChangesService;

    @Autowired
    private UPositionChangesService uPositionChangesService;

    //教学业绩
    @Autowired
    private UTeachingPerformanceService uTeachingPerformanceService;

    //教学评价
    @Autowired
    private UTeachingEvaluationService uTeachingEvaluationService;

    //科研成果
    @Autowired
    private UResearchResultsService uResearchResultsService;

    //学习进修
    @Autowired
    private UStudyAndTrainingService uStudyAndTrainingService;

    //社会兼职
    @Autowired
    private USocialPartTimeService uSocialPartTimeService;

    //荣誉获奖
    @Autowired
    private UHonorAwardService uHonorAwardService;

    @Autowired
    private SRoleOrgService sRoleOrgService;

    @Autowired
    private STeacherRoleRelationService sTeacherRoleRelationService;

    //根据教师id,返回首页统计数据
    @GetMapping("/stat")
    public String stat(String account_id, Model model, HttpServletRequest request){
        //教师id
        String id ;
        if(account_id.length()>10){
            id = DecryptionUtil.desc(account_id, teacherCommonKey,teacherCommonSecret);
        }else{
            id = account_id;
        }
        HttpSession session = request.getSession(true);
        session.setAttribute("id",id);
        UTeacherInfo utInfo = uTeacherInfoService.selectOne(new EntityWrapper<UTeacherInfo>().eq("id", id));
        if(utInfo==null) return "notExit";
        session.setAttribute("name",utInfo.getName());
        session.setAttribute("utInfo",utInfo);

        int count = sTeacherRoleRelationService.selectCount(new EntityWrapper<STeacherRoleRelation>()
                .eq("teacher_id", id)
                .eq("role_id", 0));
        if(count>0) {
            model.addAttribute("admin", true);
        }
        List<SOrg> orgs = sRoleOrgService.findOrgsByTeacherId(id);
        STeacherRoleRelation relation = sTeacherRoleRelationService.selectOne(new EntityWrapper<STeacherRoleRelation>().eq("teacher_id", id));
        //分为-1级别,1,2,3
        if(orgs==null || orgs.size()<= 0) {
            model.addAttribute("name",utInfo.getName());
            uTeacherInfoService.findDetail(id,model);
            return "teacherDetail";
        }else{
            JSONObject sumJSON = new JSONObject();
            sumJSON.put("sums",0);

            List<JSONObject> list = new ArrayList<>();

            if(relation.getRoleId()==1){
               list =  CacheUtil.allStudentResult;
            }
            if(list.isEmpty()){
                list = uTeacherInfoService.statHomeByOrgs(utInfo,orgs,sumJSON);
            }
//            List<JSONObject> list = uTeacherInfoService.statHomeByOrgs(utInfo,orgs,sumJSON);
            if(list==null || list.isEmpty()){
                model.addAttribute("name",utInfo.getName());
                uTeacherInfoService.findDetail(id,model);
                return "teacherDetail";
            }
            model.addAttribute("sums",sumJSON.getInteger("sums"));
            model.addAttribute("id",id);
            model.addAttribute("categoryes",list);
            model.addAttribute("name",utInfo.getName());

            return "teacher";
        }

    }

    @GetMapping("/list")
    public String list(String subjectCategory,String subjectAttribute,Model model,HttpServletRequest request){
        HttpSession session = request.getSession(true);
        UTeacherInfo utInfo = (UTeacherInfo) session.getAttribute("utInfo");
        String id = (String)session.getAttribute("id");
        //政治面貌
        List<UTeacherInfo> politicalStatusList = uTeacherInfoService.selectList(new EntityWrapper<UTeacherInfo>()
                .setSqlSelect("distinct(political_status)")
                .isNotNull("political_status")
                .ne("political_status",""));
        model.addAttribute("politicalStatusList",politicalStatusList);

        //

        model.addAttribute("id",id);
        model.addAttribute("subjectCategory",subjectCategory);
        model.addAttribute("subjectAttribute",subjectAttribute);
        model.addAttribute("name",utInfo.getName());
        return  "teacherList";
    }
//    @GetMapping("/list")
//    public String list(String subjectCategory,String subjectAttribute,Model model,HttpServletRequest request){
//        HttpSession session = request.getSession(true);
//        UTeacherInfo utInfo = (UTeacherInfo) session.getAttribute("utInfo");
//        String id = (String)session.getAttribute("id");
//
//        UTeacherInfo uTeacherInfo = new UTeacherInfo();
//        if(StringUtils.isNotEmpty(subjectCategory)){
//            uTeacherInfo.setSubjectCategory(subjectCategory);
//        }
//        if(StringUtils.isNotEmpty(subjectAttribute)){
//            uTeacherInfo.setSubjectAttribution(subjectAttribute);
//        }
//
//        List<SOrg> orgs = sRoleOrgService.findOrgsByTeacherId(id);
//        List<String> oneList = new ArrayList<>();
//        Map<String, List<String>> twoMap = new HashMap<>();
//        uTeacherInfoService.splitOrgs(orgs,oneList,twoMap);
//
//        PageEntity pageEntity = new PageEntity();
//        Wrapper<UTeacherInfo> wrapper = new EntityWrapper<>(uTeacherInfo);
//        if(!oneList.isEmpty()){
//            wrapper = wrapper.in("subject_category", oneList);
//        }
//        if(!twoMap.isEmpty()){
//            for (String category : twoMap.keySet()) {
//                List<String> subjectAttributeList = twoMap.get(category);
//                wrapper.or().eq("subject_category", category).in("subject_attribution", subjectAttributeList);
//            }
//        }
//        Page<UTeacherInfo> uTeacherInfoPage = uTeacherInfoService.selectPage(new Page<UTeacherInfo>(pageEntity.getPageNum(), pageEntity.getPageSize()),
//                wrapper);
//        model.addAttribute("page",uTeacherInfoPage);
//        model.addAttribute("subjectCategory",utInfo.getSubjectCategory());
//        model.addAttribute("subjectAttribution",utInfo.getSubjectAttribution());
//        model.addAttribute("id",id);
//        model.addAttribute("teacher",uTeacherInfo);
//        model.addAttribute("pageEntity",new PageEntity());
//        model.addAttribute("name",utInfo.getName());
//        return  "teacherList";
//    }


    @PostMapping(value="/queryTeacherList",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<Object> queryTeacherList(@RequestBody JSONObject param){

        UTeacherInfo uTeacherInfo = JSON.parseObject(param.toJSONString(), UTeacherInfo.class);
        Integer pageNum = param.getInteger("pageNum");
//        JSONObject result = new JSONObject();
        log.info("uTeacherInfo:"+ JSON.toJSONString(uTeacherInfo,true));
        log.info("pageNum:"+ JSON.toJSONString(pageNum,true));
        return new ResponseEntity<Object>(param, HttpStatus.OK);
    }
    @PostMapping(value = "/listByPage")
    public String listByPage(PageEntity pageEntity, UTeacherInfo teacher, Model model,HttpServletRequest request){
        HttpSession session = request.getSession(true);
        UTeacherInfo utInfo = (UTeacherInfo) session.getAttribute("utInfo");
        String id = (String)session.getAttribute("id");

        List<SOrg> orgs = sRoleOrgService.findOrgsByTeacherId(id);
        List<String> oneList = new ArrayList<>();
        Map<String, List<String>> twoMap = new HashMap<>();
        uTeacherInfoService.splitOrgs(orgs,oneList,twoMap);


        teacher.setId(null);
        Wrapper<UTeacherInfo> wrapper = new EntityWrapper<>(teacher);
        if(!oneList.isEmpty()){
            wrapper = wrapper.in("subject_category", oneList);
        }
        if(!twoMap.isEmpty()){
            for (String category : twoMap.keySet()) {
                List<String> subjectAttributeList = twoMap.get(category);
                wrapper.or().eq("subject_category", category).in("subject_attribution", subjectAttributeList);
            }
        }

        Page<UTeacherInfo> uTeacherInfoPage = uTeacherInfoService.selectPage(new Page<UTeacherInfo>(pageEntity.getPageNum(), pageEntity.getPageSize()), wrapper);
        model.addAttribute("page",uTeacherInfoPage);
        model.addAttribute("subjectCategory",utInfo.getSubjectCategory());
        model.addAttribute("subjectAttribution",utInfo.getSubjectAttribution());
        model.addAttribute("id",id);
        model.addAttribute("teacher",teacher);
        model.addAttribute("pageEntity",new PageEntity());
        model.addAttribute("name",utInfo.getName());
        return  "teacherList";
    }

    /**
     * 查询人员信息
     *
     */
    @GetMapping("/findDetail/{id}/{name}")
    public String findDetail(@PathVariable("id") String id,@PathVariable("name") String name,Model model){
        model.addAttribute("name",name);
        uTeacherInfoService.findDetail(id,model);
        return "teacherDetail";
    }

    /**
     * 查询人员信息
     *
     */
    @GetMapping("/detail")
    public String findDetail(String account_id,Model model){

        String id ;
        if(account_id.length()>10){
            id = DecryptionUtil.desc(account_id,teacherImageKey,teacherImageSecret);
        }else{
            id = account_id;
        }
        //查询人员角色
        UTeacherInfo utInfo = uTeacherInfoService.selectOne(new EntityWrapper<UTeacherInfo>().eq("id", id));
        model.addAttribute("name",utInfo.getName());
        uTeacherInfoService.findDetail(id,model);
        return "teacherDetail";
    }
}
